<template>
  <div class="select-component">
    <a-select v-model="currentValue" :allowClear="allowClear" :optionFilterProp="optionFilterProp"
      :showSearch="showSearch" :placeholder="placeholder" :mode="mode" v-bind="$attrs" v-on="$listeners">
      <a-icon slot="suffixIcon" :type="iconType" v-if="iconType" />
      <a-select-option v-for="(item, index) in dataSource" :key="index" :value="item[defaultFIeIdObj.code]">
        {{ item[defaultFIeIdObj.name] }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
export default {
  name: "SelectComponent",
  props: {
    // 双向绑定使用
    value: {
      type: [String, Number, Object, Array]
    },
    //value值匹配不到的情况下，设置自定义label值
    customLabel: {
      type: String,
    },
    placeholder: {
      type: String,
      default: () => '请选择'
    },
    dataSource: {
      type: Array,
      default: () => []
    },
    //替换下拉数据的对应字段code,name
    replaceFields: {
      type: Object,
      default: () => { }
    },
    // 支持清除
    allowClear: {
      type: Boolean,
      default: () => true
    },
    //单选模式下可搜索
    showSearch: {
      type: Boolean,
      default: false
    },
    optionFilterProp: {
      type: String,
      default: 'children'
    },
    //'default' | 'multiple' | 'tags' | 'combobox'
    mode: {
      type: String,
      default: 'default'
    },
    //图标名称
    iconType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentValue: void 0,
      defaultFIeIdObj: {
        code: 'code',
        name: 'name'
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (!newVal) {
          this.currentValue = void 0;
        } else {
          let _obj = this.dataSource.find((v) => v[this.setDefaultFIeId(this.replaceFields).code] === this.value)
          if (!_obj) {
            this.currentValue = this.customLabel;
          } else {
            this.currentValue = this.value;
          }
        }
      },
      immediate: true,
    },
    replaceFields: {
      handler(newVal) {
        this.defaultFIeIdObj = this.setDefaultFIeId(newVal);
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    setDefaultFIeId(data) {
      return data && Object.keys(data).length ? data : this.defaultFIeIdObj;
    }
  }
}
</script>

<style lang="less" scoped>
.select-component {
  .ant-select {
    width: 100%;
  }
}
</style>